package demo4;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-04
 * Time: 22:33
 */
public class Tree {

    static class Node{
        //对于多叉树来说都有它的节点值和它的孩子节点
        public int val;
        public List<Node> child;

        public Node(int val,List<Node> child){
            this.val = val;
            this.child = child;
        }
    }

    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }
    }

    //将多叉树--二叉树
    public TreeNode encode(Node root){
        if(root==null) return null;
        //将其全部挂在左树的右边界
        TreeNode head = new TreeNode(root.val);
        head.left = en(root.child);
        return head;
    }

    private TreeNode en(List<Node> childs){
        if(childs==null) return  null;
        TreeNode head = null;//二叉树的头结点
        TreeNode cur = null;//二叉树当前节点
        for(Node node : childs){
            //对于多叉树的每个节点来说,都将其它的孩子挂在这个节点的左树的右边界上
            TreeNode treeNode = new TreeNode(node.val);
            if(head==null){
                head = treeNode;//如果刚开始没有节点头指向它
            }else {
                cur.right = treeNode;//有节点往他的右边界挂
            }
            cur = treeNode;//挂完一个节点之后,cur指向当前节点
            //同时也要讲当前节点的孩子挂起
            cur.left = en(childs);
        }
        return head;
    }

    //将二叉树节点--编码为多叉树
    public Node decode(TreeNode root){
        if(root==null) return null;
        return new Node(root.val,de(root.left));
    }

    private List<Node> de(TreeNode rootL){
        List<Node> childs = new ArrayList<>();
        //将这个结点的右边界全部加到孩子集合中
        while(rootL!=null){
            Node node = new Node(rootL.val,de(rootL.left));
            childs.add(node);
            rootL = rootL.right;
        }
        return childs;
    }

}
